package com.bootdo.activiti.controller;

import com.bootdo.activiti.service.ActTaskService;
import com.bootdo.activiti.vo.HistoryVO;
import com.bootdo.activiti.vo.ProcessVO;
import com.bootdo.activiti.vo.TaskVO;
import com.bootdo.common.utils.PageUtils;
import org.activiti.engine.FormService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 代办任务
 */
@RequestMapping("activiti/task")
@RestController
public class TaskController {
    @Autowired
    RepositoryService repositoryService;
    @Autowired
    HistoryService historyService;
    @Autowired
    FormService formService;
    @Autowired
    TaskService taskService;
    @Autowired
    ActTaskService actTaskService;
    @GetMapping("goto")
    public ModelAndView gotoTask(){
        return new ModelAndView("act/task/gotoTask");
    }
    /**
     * 发起任务列表,发起任务列表应该根据身份的不同而选择不同的任务，
     * 这一点也已通过界面的Shiro权限控制，
        * */
    @GetMapping("/gotoList")
    PageUtils list(int offset, int limit) {
        List<ProcessDefinition> processDefinitions = repositoryService.createProcessDefinitionQuery()
                .listPage(offset, limit);
        int count = (int) repositoryService.createProcessDefinitionQuery().count();
        List<Object> list = new ArrayList<>();
        for(ProcessDefinition processDefinition: processDefinitions){
            list.add(new ProcessVO(processDefinition));
        }

        PageUtils pageUtils = new PageUtils(list, count);
        return pageUtils;
    }

    @GetMapping("/form/{procDefId}")
    public void startForm(@PathVariable("procDefId") String procDefId  ,HttpServletResponse response) throws IOException {
        String formKey = actTaskService.getFormKey(procDefId, null);
        response.sendRedirect(formKey);
    }
    /**
     * 审批，查询任务详情
     * */
    @GetMapping("/form/{procDefId}/{taskId}")
    public void form(@PathVariable("procDefId") String procDefId,@PathVariable("taskId") String taskId ,HttpServletResponse response) throws IOException {
        // 获取流程XML上的表单KEY
        String formKey = actTaskService.getFormKey(procDefId, taskId);
        response.sendRedirect(formKey+"/"+taskId);//跳转界面
    }

    @GetMapping("/todo")
    ModelAndView todo(){
        return new ModelAndView("act/task/todoTask");
    }
    /**
     * 代办任务列表
     * 查询act_ru_task的任务
     *
     *  *    act_ru_task
     *  *      1、说明
     *  *         代表正在执行的任务表
     *  *         该表是一个临时表，如果当前任务被完成以后，任务在这张表中就被删除掉了
     *  *      2、字段
     *  *          id_:  主键    任务ID
     *  *          execution_id_:执行ID  
     *  *              根据该ID查询出来的任务肯定是一个
     *  *          proc_inst_id:piid
     *  *              根据该id查询出来的任务
     *  *                 如果没有并发，则是一个
     *  *                 如果有并发，则是多个
     *  *          name_:任务的名称
     *  *          assignee_:任务的执行人
     *  ID     REV  execution_id_       proc_inst_id    proc_def_id         NAME                            ASSIGNEE_
     * 155007	1	155001	            155001	        salary:5:152509	    薪酬主管初审			audit		admin		50	2018-12-01 17:26:11			1
     *
     *  根据adminassignee_查询代办任务，这个代办任务可以弄成   用户角色(sys_role)的关联，获取用户的role_sign，管理员是role,普通用户是null(未涉及)
     * proc_def_id，部署id,act_ru_procdef的逐渐
     * salary:5:152509	1	http://www.activiti.org/test	流程审批测试流程	salary	5	152506	流程审批测试流程.bpmn20.xml.bpmn20.xml	流程审批测试流程.bpmn20.xml.salary.png		1	1	1
     * */
    @GetMapping("/todoList")
    List<TaskVO> todoList(){
        List<Task> tasks = taskService.createTaskQuery().taskAssignee("admin").list();
        List<TaskVO> taskVOS =  new ArrayList<>();
        for(Task task : tasks){
            TaskVO taskVO = new TaskVO(task);
            taskVOS.add(taskVO);
        }
        return taskVOS;
    }
    /**
     * 查询admin角色已办任务
     * */
    @GetMapping("/completeList")
    PageUtils completeList(int offset, int limit){
        List<HistoricActivityInstance> list1 = historyService.createHistoricActivityInstanceQuery()
                //.processInstanceId("salary:3:135067") // 用流程实例id查询
                .finished().list();
        List<TaskVO> taskVOS =  new ArrayList<>();
        int count = (int) repositoryService.createProcessDefinitionQuery().count();

        List<Object> list = new ArrayList<>();
        for(HistoricActivityInstance history: list1){
            list.add(new HistoryVO(history));
        }

        PageUtils pageUtils = new PageUtils(list, count);
        return pageUtils;
    }

    /**
     * 读取带跟踪的图片
     */
    @RequestMapping(value = "/trace/photo/{procDefId}/{execId}")
    public void tracePhoto(@PathVariable("procDefId") String procDefId, @PathVariable("execId") String execId, HttpServletResponse response) throws Exception {
        InputStream imageStream = actTaskService.tracePhoto(procDefId, execId);

        // 输出资源内容到相应对象
        byte[] b = new byte[1024];
        int len;
        while ((len = imageStream.read(b, 0, 1024)) != -1) {
            response.getOutputStream().write(b, 0, len);
        }
    }


}
